package org.opens.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;
import org.opens.netty.util.ByteUtil;

import java.util.List;

@Slf4j
public class ByteBufToFrameDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        // 转换对象
        Frame frame = new Frame();
        frame.setType(ByteUtil.unsignedHexStringZeroFill(ByteUtil.byteToHexString(msg.getByte(4)), 1, ByteUtil.B));
        frame.setHex(ByteUtil.byteArrayToHexString(ByteBufUtil.getBytes(msg)));
        out.add(frame);

        // 释放内存
        // 不需要手动释放 ByteBuf，Netty 会自动管理
        //msg.release();
    }

}
